<?php
// echo '<pre>';
define('IMAGE_PATH','./images/');
if(!file_exists(IMAGE_PATH)) {
	mkdir(IMAGE_PATH,0775);
}
$layers = stripslashes(trim($_REQUEST['layers']));
$layers = json_decode($layers, true);

if(is_array($layers) && count($layers)) {
	$path = createCompositeImage($layers);
	if($path !== false) {
		$image = @file_get_contents($path);
		header("content-type: image/jpeg");
		echo $image;
	}
} else {
	echo '<br> Wrong Parameter List Supplied!';
}

function createCompositeImage($layers) {
	if(is_array($layers) && count($layers)) {
		$counter = 0;
		$imgArray = array();
		$id = uniqid();
		foreach($layers as &$layer){
			$counter++;
			$url = $layer['url'];
			unset($layer['url']);
			$layer['width'] = $_REQUEST['width'];
			$layer['height'] = $_REQUEST['height'];

			if (strpos($url, "?") === false) {
				$layer['url'] = $url . '?' . http_build_query($layer, '', '&');
			} else {
				$layer['url'] = $url . '&' . http_build_query($layer, '', '&');
			}
			
			$res = @file_get_contents($layer['url']);
			$iPath = IMAGE_PATH . $id . $counter . getExtension($layer['format']);
#			print $iPath;
			file_put_contents($iPath, $res);

			// Test if file we just saved is an image if not stop and show error.
			if (!is_array(getimagesize($iPath))) {
//				print "There was an error due to one of the geoservers not being able to generate an image.<br>Url: <a href=\"" . $layer['url'] . "\">" . $layer['url'] . "</a>";
//				exit();
			} else {		
				$layer['path'] = $iPath;
				$imgArray[] = array('path' => $iPath, 'opacity' => $layer['opacity'] * 100);
			}
		}
		
		if (count($imgArray) == 0) {
			print "There was an error due to one of the geoservers not being able to generate an image.";
			exit();
		}
		$destImage = IMAGE_PATH . $id . '.jpg';
		$ret = createImage($imgArray, $destImage);
		return $ret;
	}
	return false;
}

function getExtension($format) {
	switch(@strtolower($format)) {
		case 'image/png': $ext = '.png'; break;
		case 'image/jpeg': $ext = '.jpg'; break;
		case 'image/gif': $ext = '.gif'; break;
	}
	return $ext;
}

function createImage($imgArray, $destImage) {
	if(is_array($imgArray) && count($imgArray)) {
		if (count($imgArray) == 1) {
			return($imgArray[0]['path']);
		}
		for($i=0;$i< count($imgArray) - 1;$i++) {
			$img = ($i == 0) ? $imgArray[$i]['path'] : $destImage;
			$opacity = ($i == 0) ? 100 : $imgArray[$i]['opacity'];
			$cmd = " composite -gravity center -dissolve {$imgArray[$i+1]['opacity']}x$opacity  {$imgArray[$i+1]['path']} $img $destImage";
			system($cmd);
// 			echo '<br>' . $cmd;
		}
		return $destImage;
	}
	return false;
}
?>